package com.lfy.kcat.content.xxl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.lfy.kcat.content.config.XxlJobConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author leifengyang
 * @version 1.0
 * @date 2025/9/15 15:28
 * @description:
 */
@Service
public class XxlHttp {

    @Autowired
    XxlJobConfig xxlJobConfig;

    /**
     * 机器人登录xxl-job
     * @return
     */
    public HttpCookie robotLogin(){
        Map<String,Object> map = new HashMap<>();
        map.put("userName",xxlJobConfig.getUsername());
        map.put("password",xxlJobConfig.getPassword());
        //1、发送请求，模拟登录 xxl-job
        HttpResponse response = HttpUtil.createPost(
            xxlJobConfig.getAdminAddresses()+"/auth/doLogin")
            .form(map)
            .execute();

        //2、拿到响应的cookie
        List<HttpCookie> cookies = response.getCookies();
        return cookies.get(0);
    }

    public HttpResponse triggerJob(HttpCookie cookie, Map<String,Object> map){
        String url = xxlJobConfig.getAdminAddresses()+"/jobinfo/trigger";
        HttpResponse response = HttpUtil.createPost(url)
            .form(map)
            .cookie(cookie)
            .execute();
        return response;
    }
}
